package com.ruoyi.common.s7.ST30B;

import com.alibaba.fastjson2.JSON;
import com.github.s7connector.api.DaveArea;
import com.github.s7connector.api.S7Connector;
import com.ruoyi.common.s7.BaseVo;
import com.ruoyi.common.s7.ExchangeIntf;
import com.ruoyi.common.s7.ST30A.ST30AHandle;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;

@Slf4j
public class ST30BExchange implements ExchangeIntf {
    public  static int areaNumber = 5403;
    public static String ipAddress = "192.168.0.51";
    public static void main(String[] args) {
        ST30BHandle sT30BHandle =   new ST30BHandle();
        S7Connector s7ReadConnector = sT30BHandle.initConnect(ipAddress);
        ST30BVo st30Vo = sT30BHandle.read(s7ReadConnector, areaNumber);
        if(st30Vo.getNewPnFlag() ==1){
            log.info(JSON.toJSONString(st30Vo));
            try {
                s7ReadConnector.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }

    /**
     *
     * @return
     */
    @Override
    public BaseVo readPLC() {
        ST30BHandle sT30BHandle =    new ST30BHandle();
        S7Connector s7Connector = sT30BHandle.initConnect(ipAddress);
        ST30BVo resultVo = sT30BHandle.read(s7Connector, areaNumber);
        try {
            s7Connector.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return resultVo;
    }

    /**
     *
     * @param paramVo
     */
    @Override
    public void writePLC(BaseVo paramVo) {
        ST30BVo st30BVo = (ST30BVo) paramVo;
        ST30AHandle sT30Handle =   new ST30AHandle();
        S7Connector s7Connector = sT30Handle.initConnect(ipAddress);
        if(st30BVo.getSkipFlag()==2){
            //跳站标记为已跳站
            byte[] data = new byte[1];
            data[0] = st30BVo.getSkipFlag();
            s7Connector.write(DaveArea.DB, areaNumber, 142, data);
        }else{
            //写入已读取标记
            byte[] data = new byte[1];
            data[0] = st30BVo.getNewTotalFlowResultFlag();
            s7Connector.write(DaveArea.DB, areaNumber, 141, data);
        }
        try {
            s7Connector.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
